<template>
    <Card dis-hover :bordered="false">
        <div style="
                height: 60px;
                display: flex;
                align-items: center;
                justify-content: space-between;
            ">
            <Input @on-enter="enterWord" v-model="keyWord" v-width="360" clearable @on-clear="enterWord"
                placeholder="请输入搜索关键词" />
            <Button v-hasC="{
                    name: 'automation-tag-add-tag-auto',
                    flag: 'v1/automation/tag/add-tag-auto',
                }" class="ivu-fr" type="primary" @click="handleOpenDrawer(-1)">新增</Button>
        </div>

        <div class="i-table-no-border">
            <Table highlight-row ref="table" :columns="columns" :loading="loading" :data="data">
                <template slot="tag" slot-scope="{ row }">
                    <tag v-for="item in row.tags_name.split(',')" :key="item.index">{{ item }}</tag>
                </template>
                <template slot="choose_type" slot-scope="{ row }">
                    <div>
                        {{ row.choose_type === "1" ? "聊天记录" : "模块字段" }}
                    </div>
                </template>
                <template slot="matched_pattern" slot-scope="{ row }">
                    <div>
                        {{
                        row.matched_pattern
                        ? row.matched_pattern === "1"
                        ? "所有条件"
                        : "任意条件"
                        : ""
                        }}
                    </div>
                </template>
                <template slot="status" slot-scope="{ row }">
                    <Badge v-if="row.status === '1'" status="success" text="正常"></Badge>
                    <Badge v-else status="error" text="停用"></Badge>
                </template>
                <template slot-scope="{ row }" slot="info">
                    <a v-hasC="{
                            name: 'automation-tag-update-tag-auto',
                            flag: 'v1/automation/tag/update-tag-auto',
                        }" href="javaScript:;" @click="handleOpenDrawer(row)">编辑</a>
                    <Divider v-hasCC="[
                            {
                                name: 'automation-tag-update-tag-auto',
                                flag: 'v1/automation/tag/update-tag-auto',
                            },
                            {
                                name: 'automation-tag-del-tag-auto',
                                flag: 'v1/automation/tag/del-tag-auto',
                            },
                        ]" type="vertical" />
                    <a v-hasC="{
                            name: 'automation-tag-del-tag-auto',
                            flag: 'v1/automation/tag/del-tag-auto',
                        }" href="javaScript:;" @click="handleDetele(row)">删除</a>
                </template>
            </Table>
            <div class="ivu-mt ivu-text-center">
                <Page show-total show-elevator show-sizer :total="total" :current.sync="params.page"
                    :page-size="params.pageSize" :page-size-opts="pageOpts" @on-change="formSize"
                    @on-page-size-change="formChangePage" />
            </div>
            <Modal width="680" v-model="modal" :title="edit ? `编辑` : `新增`" :mask-closable="false"
                @on-cancel="handleDrawerCancel(modalname)">
                <Form :label-width="118" :ref="modalname" :model="formItem" :rules="ruleCustom" :key="reset">
                    <FormItem label="选择类型:" prop="type">
                        <RadioGroup v-model="formItem.type">
                            <Radio v-for="(item, index) in titleList" :key="index" :label="item.value">{{ item.label }}
                            </Radio>
                        </RadioGroup>
                    </FormItem>
                    <FormItem v-if="formItem.type === 2" label="匹配模式:">
                        <RadioGroup v-model="formItem.matching">
                            <Radio v-for="(item, index) in TJList" :key="index" :label="item.value">{{ item.label }}
                            </Radio>
                        </RadioGroup>
                    </FormItem>
                    <FormItem v-if="formItem.type === 2" label="选择条件:">
                        <Row v-for="(item, index) in formItem.isChooseList" :key="index"
                            :style="{'margin-top':index===0?'0':'20px'}">
                            <Col span="6">
                            <FormItem :rules="{required: true, message: '请完善', trigger: 'change'}"
                                :prop="'isChooseList.' + index + '.field'" :key="index">
                                <Select v-width="118" v-model="item.field" @on-change="changeFirst(index)">
                                    <Option v-for="(item1, index1) in chooseList" :key="index1" :value="item1.value">{{
                                        item1.title }}</Option>
                                </Select>
                            </FormItem>
                            </Col>
                            <Col span="6">
                            <FormItem :rules="{required: true, message: '请完善', trigger: 'change'}"
                                :prop="'isChooseList.' + index + '.operation'">
                                <Select v-width="118" v-model="item.operation">
                                    <Option v-for="(item2, index2) in operationList[index]" :key="index2"
                                        :value="item2.value">{{ item2.title }}
                                    </Option>
                                </Select>
                            </FormItem>
                            </Col>
                            <Col span="6">
                            <FormItem :rules="isOneRule(index)" :prop="'isChooseList.' + index + '.content'">
                                <Input v-model="item.content" v-width="118" />
                            </FormItem>
                            </Col>
                            <Col span="6">
                            <Button @click="deleteItem(index)" v-if="index >= 1">删除</Button>
                            </Col>
                        </Row>
                    </FormItem>
                    <div v-if="formItem.type === 2" style="
                            display: flex;
                            box-sizing: border-box;
                            padding-left: 120px;
                        ">
                        <Button style="margin-bottom: 30px;" @click="addIsChooseList">+新增</Button>
                    </div>

                    <FormItem v-show="formItem.type === 1" label="请输入关键词:" prop="keyWord">
                        <Input type="textarea" v-model="formItem.keyWord" placeholder="支持多个关键词，请使用“ , ”分隔" />
                        <Checkbox v-model="formItem.single">仅应用于对方发送的消息</Checkbox>
                    </FormItem>
                    <FormItem label="请选择标签:" prop="tagList">
                        <Select multiple v-model="formItem.tagList">
                            <OptionGroup v-for="(item, index) in tag" :key="index" :label="item.label">
                                <Option v-for="(items, index1) in item.children" :value="items.value" :key="index1">{{
                                    items.label }}</Option>
                            </OptionGroup>
                        </Select>
                    </FormItem>
                    <FormItem label="有效期:" prop="time">
                        <RadioGroup v-model="formItem.time">
                            <Radio label="长期有效">长期有效</Radio>
                            <br />
                            <Radio label="日期选择">
                                在
                                <DatePicker :editable="false" :options="options" v-model="formItem.times"
                                    :disabled="formItem.time === '长期有效'" v-width="150" format="yyyy-MM-dd"
                                    class="ivu-ml-8 ivu-mr-8" type="date" />后失效
                            </Radio>
                        </RadioGroup>
                    </FormItem>
                    <FormItem label="状态:" v-if="edit">
                        <Switch v-model="formItem.status" />
                    </FormItem>
                </Form>
                <div slot="footer">
                    <Button @click="handleDrawerCancel(modalname)">取消</Button>
                    <Button type="primary" :loading="remarksloading" @click="handleSubmit(modalname)">确定</Button>
                </div>
            </Modal>
        </div>
    </Card>
</template>

<script>
    import dayjs from "dayjs";
    import {
        autoTagList,
        AddAutoTag,
        deleteAutoTag,
        editAutoTag,
    } from "@/api/TApi/index.js";
    import { callbackgetparamslist } from "@/api/hqapi/index.js";
    export default {
        /*  import引入的组件注入到components对象中使用  */
        components: {},
        data() {
            const validateTime = (rule, value, callback) => {
                //   console.log(value);
                if (value === "长期有效") {
                    callback();
                } else {
                    if (this.formItem.times === "") {
                        callback(new Error("请选择有限时间"));
                    } else {
                        callback();
                    }
                }
            };
            const validateWord = (rule, value, callback) => {
                if (this.formItem.type === 2) {
                    callback();
                } else {
                    if (value === "") {
                        callback(new Error("请输入关键词"));
                    } else {
                        callback();
                    }
                }
            };
            const validateIsChooseList = (rule, value, callback) => {
                let obj = value[value.length - 1];
                if (
                    obj.content === "" ||
                    obj.field === "" ||
                    obj.operation === ""
                ) {
                    callback(new Error("请完善条件"));
                } else {
                    callback();
                }
            };
            return {
                options: {
                    disabledDate(date) {
                        return date && date.valueOf() < Date.now();
                    },
                },
                // 模态框验证规则
                ruleCustom: {
                    keyWord: {
                        required: true,
                        validator: validateWord,
                        trigger: "blur",
                    },
                    tagList: {
                        required: true,
                        type: "array",
                        message: "请选择标签",
                        trigger: "change",
                    },
                    time: {
                        validator: validateTime,
                        trigger: "change",
                        required: true,
                    },
                    isChooseList: {
                        validator: validateIsChooseList,
                        trigger: "blur",
                        required: true,
                    },
                },
                total: 0, //  分页总数
                remarksloading: false,
                pageOpts: [10, 20, 30, 50], //  分页每页数量
                params: { page: 1, pageSize: 10 }, //  请求参数
                edit: true, //  编辑true,新增false
                loading: false, //  加载中
                modal: false, //  模态框开启属性
                modalname: "formItem",
                isEdit: "",
                grid: { xl: 4, lg: 8, md: 12, sm: 24, xs: 24 }, //  layout布局
                columns: [
                    {
                        title: "标签",
                        slot: "tag",
                        minWidth: 138,
                        fixed: "left",
                    },
                    {
                        title: "触发关键词",
                        key: "keyword",
                        minWidth: 138,
                    },
                    {
                        title: "类型",
                        slot: "choose_type",
                        //   key: "choose_type",
                        width: 138,
                    },
                    {
                        title: "匹配模式",
                        slot: "matched_pattern",
                        //   key: "matched_pattern",
                        width: 118,
                    },
                    {
                        title: "有效时间",
                        key: "expire_time",
                        width: 168,
                    },
                    {
                        title: "状态",
                        slot: "status",
                        width: 100,
                    },
                    { title: "操作", slot: "info", width: 138 },
                ], // 列表表头
                data: [], // 列表数据
                keyWord: "",
                chooseList: [],
                operationList: [],
                operationList1: [
                    {
                        title: "等于",
                        value: "=",
                    },
                    {
                        title: "不等于",
                        value: "!=",
                    },
                    {
                        title: "小于等于",
                        value: "<=",
                    },
                    {
                        title: "大于等于",
                        value: ">=",
                    },
                ],
                operationList2: [
                    {
                        title: "等于",
                        value: "=",
                    },
                ],
                tag: [],
                titleList: [
                    {
                        label: "聊天记录",
                        value: 1,
                    },
                    {
                        label: "模块字段",
                        value: 2,
                    },
                ],
                TJList: [
                    {
                        label: "所有条件",
                        value: 1,
                    },
                    {
                        label: "任意条件",
                        value: 2,
                    },
                ],
                reset: 10,
                formItem: {
                    type: 1,
                    single: true,
                    matching: 1,
                    isChooseList: [
                        {
                            field: "",
                            content: "",
                            operation: "",
                        },
                    ],
                    status: true,
                    tagList: [],
                    keyWord: "",
                    times: "",
                    time: "长期有效",
                }, // 模态框数据
            };
        },
        /* 监听属性 类似于data概念 */
        computed: {
            isOneRule() {
                return function (index) {
                    let type = this.formItem.isChooseList[index].field
                    if (type === "age") {
                        return {
                            validator: (rule, value, callback) => {
                                if (value) {
                                    if (!(/(^[1-9]\d*$)/.test(value))) {
                                        callback(new Error('请输入正整数'));
                                    } else {
                                        callback();
                                    }
                                } else {
                                    callback(new Error('请完善'));
                                }

                            }, trigger: 'change'
                        }

                    } else if (type === "assign_num" || type === "callback_count") {
                        return {
                            validator: (rule, value, callback) => {
                                if (value) {
                                    if (!(/(^[0-9]\d*$)/.test(value))) {
                                        callback(new Error('请输入整数'));
                                    } else {
                                        callback();
                                    }
                                } else {
                                    callback(new Error('请完善'));
                                }

                            }, trigger: 'change'
                        }
                    } else {
                        return { required: true, message: '请完善', trigger: 'change' }
                    }
                }
            }
        },
        watch: {},
        /* 创建完成能访问this实例 */
        created() { },
        /* 函数方法集合 */
        methods: {
            _basetagsindex() {
                callbackgetparamslist().then((res) => {
                    this.tag = res.tags_list;
                });
            },

            changeFirst(index) {
                let title = this.formItem.isChooseList[index].field;
                let type = this.chooseList.find((ee) => ee.value === title).type;
                if (type === "1") {
                    this.operationList[index] = this.operationList2;
                } else {
                    this.operationList[index] = this.operationList1;
                }
            },
            deleteItem(index) {
                this.formItem.isChooseList.splice(index, 1);
            },
            enterWord() {
                this.askData();
            },
            addIsChooseList() {
                this.formItem.isChooseList.push({
                    field: "",
                    content: "",
                    operation: "",
                });
            },
            /* @函数功能: 初始化 */
            initial() {
                this.askData();
            },
            /* @函数功能: 请求数据 */
            askData() {
                let paramsS = {
                    keyword: this.keyWord,
                    ...this.params,
                };
                this.loading = true;
                autoTagList(paramsS).then((res) => {
                    this.chooseList = res.choose;
                    this.data = res.list;
                    this.total = res.total;
                    this.loading = false;
                });
            },
            /* @函数功能: 分页 */
            formSize(e) {
                this.params.page = e;
                this.askData();
            },
            /* @函数功能: 每页数量 */
            formChangePage(e) {
                this.params.pageSize = e;
                this.askData();
            },
            /* @函数功能: 打开新增或编辑 */
            handleOpenDrawer(row) {
                // this.$refs.formItem.resetFields()
                this.formItem = {
                    type: 1,
                    single: true,
                    matching: 1,
                    isChooseList: [
                        {
                            field: "",
                            content: "",
                            operation: "",
                        },
                    ],
                    status: true,
                    tagList: [],
                    keyWord: "",
                    times: "",
                    time: "长期有效",
                }
                if (row === -1) {
                    this.edit = false;
                } else {
                    this.isEdit = row;
                    this.edit = true;
                    this.formItem.type = Number(row.choose_type);
                    this.formItem.time =
                        row.expire_time === "2999-12-31 23:59:59"
                            ? "长期有效"
                            : "日期选择";
                    this.formItem.times =
                        row.expire_time === "2999-12-31 23:59:59"
                            ? ""
                            : row.expire_time.slice(0, 10);
                    this.formItem.matching = row.matched_pattern === "2" ? 2 : 1;
                    this.formItem.tagList = row.tags_id.split(",");
                    this.formItem.keyWord = row.keyword;
                    this.formItem.status = row.status === "1" ? true : false;
                    if (row.choose_type === "2") {
                        this.formItem.isChooseList = JSON.parse(row.field_content);
                        this.formItem.isChooseList.forEach((ee, index) => {
                            let flag = this.chooseList.find(
                                (eee) => eee.value === ee.field
                            ).type;
                            if (flag === "1") {
                                this.operationList[index] = this.operationList2;
                            } else {
                                this.operationList[index] = this.operationList1;
                            }
                        });
                    } else {
                        this.formItem.single = row.send_tips === "1" ? true : false;
                    }
                }
                this.modal = true;
            },
            /* @函数功能: 新增或编辑提交 */
            handleSubmit(name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        let params = {
                            choose_type: this.formItem.type,
                            tags: this.formItem.tagList.join(","),
                            expire_time:
                                this.formItem.time === "长期有效"
                                    ? "2999-12-31 23:59:59"
                                    : dayjs(this.formItem.times).format(
                                        "YYYY-MM-DD"
                                    ) +
                                    " " +
                                    "23:59:59",
                        };
                        this.remarksloading = true;
                        if (this.formItem.type === 1) {
                            params.matched_pattern = "";
                            params.keyword = this.formItem.keyWord;
                            params.send_tips =
                                this.formItem.single === true ? 1 : 0;
                        }
                        if (this.formItem.type === 2) {
                            params.matched_pattern = this.formItem.matching;
                            params.field_content = JSON.stringify(
                                this.formItem.isChooseList
                            );
                        }
                        switch (this.edit) {
                            case true:
                                {
                                    params.id = this.isEdit.id;
                                    params.status =
                                        this.formItem.status === true ? 1 : 0;
                                    editAutoTag(params).then((res) => {
                                        this.handleDrawerCancel("formItem");
                                        this.$Message.success("编辑成功");
                                        this.remarksloading = false;
                                        this.askData();
                                    }).catch(() => {
                                        this.remarksloading = false;
                                    });
                                }
                                break;
                            case false:
                                {
                                    AddAutoTag(params).then((res) => {
                                        this.handleDrawerCancel("formItem");
                                        this.$Message.success("添加标签成功");
                                        this.remarksloading = false;
                                        this.askData();
                                    }).catch(() => {
                                        this.remarksloading = false;
                                    });
                                }
                                break;
                        }
                    }
                });
            },
            /* @函数功能: 取消新增或编辑 */
            handleDrawerCancel(name) {
                this.reset = Math.random() * 100
                this.modal = false;
            },
            handleDetele(data) {
                this.$Modal.confirm({
                    title: "删除提示",
                    content: "删除后将不能恢复，已经打上的标签将保持不变",
                    onOk: () => {
                        deleteAutoTag({
                            id: data.id,
                        }).then((res) => {
                            this.$Message.success("删除成功");
                            this.askData();
                        });
                    },
                });
            },
        },
        /* 挂载完成能访问DOM元素 */
        mounted() {
            this.initial();
            this._basetagsindex();
        },
        /* 创建之前 */
        beforeCreate() { },
        /* 挂载之前 */
        beforeMount() { },
        /* 更新之前 */
        beforeUpdate() { },
        /* 更新之后 */
        updated() { },
        /* 销毁之前 */
        beforeDestroy() { },
        /* 销毁完成 */
        destroyed() { },
        /* 有keep-alive缓存即会触发 */
        activated() { },
    };
</script>

<style lang="less" scoped>
    /deep/.ivu-icon-ios-loading {
        display: none !important;
    }
</style>